import React, {useCallback, useMemo} from "react";
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
import "./index.css";
import Header from "../common/header";
import Journey from "../components/journey";
import DepartureDate from "../components/departure-date";
import HighSpeed from "../components/high-speed";
import Submit from "../components/submit";
import CitySelector from "../common/city-selector";
import DateSelector from "../common/date-selector";
import {transformTime} from "../utils";
import {
  exchangeFromTo,
  showCitySelector,
  hideCitySelector,
  fetchCityData,
  setSelectedCity,
  showDateSelector,
  hideDateSelector,
  setDepartDate,
  toggleHighSpeed
} from "./store/actions";

function App(props) {
  const {
    from,
    to,
    isCitySelectorVisible,
    cityData,
    isLoadingCityData,
    highSpeed,
    dispatch,
    departDate,
    isDateSelectorVisible
  } = props;

  const onBack = useCallback(() => {
    window.history.back();
  }, []);

  const journeyCBS = useMemo(() => {
    return bindActionCreators(
      {
        exchangeFromTo,
        showCitySelector
      },
      dispatch
    );
  }, [dispatch]);

  const departureCBS = useMemo(() => {
    return bindActionCreators(
      {
        onClick: showDateSelector
      },
      dispatch
    );
  }, [dispatch]);

  const citySelectorCBS = useMemo(() => {
    return bindActionCreators(
      {
        onBack: hideCitySelector,
        fetchCityData,
        onSelect: setSelectedCity
      },
      dispatch
    );
  }, [dispatch]);

  const dateSelectorCBS = useMemo(() => {
    return bindActionCreators(
      {
        onBack: hideDateSelector
      },
      dispatch
    );
  }, [dispatch]);

  const highSpeedCBS = useMemo(() => {
    return bindActionCreators(
      {
        toggle: toggleHighSpeed
      },
      dispatch
    )
  }, [dispatch])

  const onSelectDate = useCallback(day => {
    if (!day || day < transformTime()) return;

    dispatch(setDepartDate(day));
    dispatch(hideDateSelector());
  }, [dispatch]);

  return (
    <div>
      <div className="header-wrapper">
        <Header title="火车票" onBack={onBack}/>
      </div>

      <form className="form" action="./query.html">
        <Journey from={from} to={to} {...journeyCBS} />
        <DepartureDate time={departDate} {...departureCBS} />
        <HighSpeed highSpeed={highSpeed} {...highSpeedCBS} />
        <Submit/>
      </form>

      <CitySelector
        show={isCitySelectorVisible}
        cityData={cityData}
        isLoading={isLoadingCityData}
        {...citySelectorCBS}
      />

      <DateSelector
        show={isDateSelectorVisible}
        onSelect={onSelectDate}
        {...dateSelectorCBS}
      />
    </div>
  );
}

const mapStateToProps = state => state;

const mapDispatchToProps = dispatch => ({dispatch});

export default connect(mapStateToProps, mapDispatchToProps)(App);
